package com.resou.reader.discovery.choicenes.fragment;


import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.resou.reader.R;
import com.resou.reader.api.entry.ChoiceneBookListBean;
import com.resou.reader.base.ResouBaseFragment;
import com.resou.reader.discovery.bookdetail.BookListActivity;
import com.resou.reader.discovery.choicenes.adapter.ChoiceneBookAdapter;
import com.resou.reader.utils.ToastUtil;
import com.resou.reader.utils.eventbus.MessageEvent;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 精品书单男生
 */
public class FragmentBoy extends ResouBaseFragment<ChoiceneBookPresenter> implements IChoiceneBookFragmentContract.IChoiceneBookView, OnRefreshListener {
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.mSmartRefreshLayout)
    SmartRefreshLayout mSmartRefreshLayout;
    ChoiceneBookAdapter choiceneBookAdapter;
    RelativeLayout rlHeader;
    ImageView ivLeftIMG;
    TextView tvLeftTitle;
    ImageView ivRightIMG;
    TextView tvRightTitle;
    String gender = "1";
    String type;
    String category;
    String label;
    int page;
    View view;

    public FragmentBoy() {
    }

    public static FragmentBoy fragmentBoy;

    public static FragmentBoy newInstance() {
        if (null == fragmentBoy) {
            fragmentBoy = new FragmentBoy();
        }
        return fragmentBoy;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_fragment_boy;
    }

    @Override
    protected void initPresenter() {
        mPresenter = new ChoiceneBookPresenter(this);
    }

    @Override
    protected void initView() {
        mSmartRefreshLayout.setOnRefreshListener(this);
        mSmartRefreshLayout.setEnableLoadMore(false);
//        mSmartRefreshLayout.setEnableFooterFollowWhenLoadFinished(true);
        ClassicsFooter.REFRESH_FOOTER_NOTHING = "已经全部加载完毕";
        List<ChoiceneBookListBean.UnRecommendBean.BookListBean> list = new ArrayList<>();
        getHeaderView();
        choiceneBookAdapter = new ChoiceneBookAdapter(R.layout.adapterchoicenebook_list, list);
        choiceneBookAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(choiceneBookAdapter);
        choiceneBookAdapter.setPreLoadNumber(4);
        choiceneBookAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                page++;
                mPresenter.quearChoiceneBookData(gender, type, category, label, page);
            }
        }, mRecyclerView);
        choiceneBookAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                ChoiceneBookListBean.UnRecommendBean.BookListBean bookListBean = (ChoiceneBookListBean.UnRecommendBean.BookListBean) adapter.getData().get(position);
                String[] urls = bookListBean.getBookListUrl().split(",");
                BookListActivity.start(getContext(), bookListBean.getBookListId(), urls[0] != null ? urls[0] : "");
            }
        });

    }

    @Override
    protected void retryRefreshData() {

    }

    @Override
    public BaseQuickAdapter getAdapter() {
        return choiceneBookAdapter;
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        page = 0;
        choiceneBookAdapter.getData().clear();
        mPresenter.quearChoiceneBookData(gender, type, category, label, page);
    }

    @Override
    public void initData() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        page = 0;
        mPresenter.quearChoiceneBookData(gender, type, category, label, page);
    }

    @Override
    public void showContent() {

    }

    @Override
    public void showProgress() {

    }

    @Override
    public void showError(Throwable throwable) {
        ToastUtil.makeShortToast("网络异常");
//        Toast.makeText(mActivity, "" + throwable.getMessage(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showEmpty() {
        choiceneBookAdapter.setHeaderAndEmpty(true);
        choiceneBookAdapter.setEmptyView(getEmptyView());
    }

    @Override
    public void showShowRecommendBean(List<ChoiceneBookListBean.RecommendBean> recommendBean) {
        if (choiceneBookAdapter.getHeaderLayout() == null) {
            choiceneBookAdapter.addHeaderView(view);
        }
        try {
            Glide.with(getActivity()).load(recommendBean.get(0).getBookListUrl() == null ? "" : recommendBean.get(0).getBookListUrl()).dontTransform().into(ivLeftIMG);
            tvLeftTitle.setText(recommendBean.get(0).getBookListName() + "");
            Glide.with(getActivity()).load(recommendBean.get(1).getBookListUrl() == null ? "" : recommendBean.get(1).getBookListUrl()).dontTransform().into(ivRightIMG);
            tvRightTitle.setText(recommendBean.get(1).getBookListName() + "");
            if (!ivLeftIMG.hasOnClickListeners()) {
                ivLeftIMG.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        BookListActivity.start(getContext(), recommendBean.get(0).getBookListId(), recommendBean.get(0).getBookListUrl());
                    }
                });
            }
            if (!ivRightIMG.hasOnClickListeners()) {
                ivRightIMG.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        BookListActivity.start(getContext(), recommendBean.get(1).getBookListId(), recommendBean.get(1).getBookListUrl());
                    }
                });
            }
        } catch (Exception e) {
        }
    }

    @Override
    public void recommendEmpty() {
        choiceneBookAdapter.removeAllHeaderView();
    }

    @Override
    public void showShowUnRecommendBean(List<ChoiceneBookListBean.UnRecommendBean.BookListBean> recommendBean) {
        if (page == 0) {
            mSmartRefreshLayout.finishRefresh(true);
            Log.i("showDatas", "showShowUnRecommendBean: " + recommendBean.size());
            choiceneBookAdapter.setNewData(recommendBean);
        } else {
            choiceneBookAdapter.addData(recommendBean);
        }
    }

    @Override
    public void unRecommendEmpty() {
    }

    /**
     * 接受主@ChoiceneBookActivity 的选择的标签属性
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(MessageEvent event) {
        mRecyclerView.smoothScrollToPosition(0);
        if (event != null && event.getGender().equals("1")) {
            this.label = event.getLabel();
            this.category = event.getCategory();
            this.type = event.getType();
            page = 0;
            Log.i("OkHttp: <", "Event: " + category);
            mPresenter.quearChoiceneBookData(gender, type, category, label, page);
        } else if (event.getGender().equals("4")) {
            type = "";
            category = "";
            label = "";
//            page = 0;
//            mPresenter.quearChoiceneBookData(gender, type, category, label, page);
//            mSmartRefreshLayout.autoRefresh();
//            mSmartRefreshLayout.setNoMoreData(false);
        }

    }

    @Override
    public SmartRefreshLayout getSmartRefreshLayout() {
        return mSmartRefreshLayout;
    }

    public void getHeaderView() {
        view = LayoutInflater.from(getContext()).inflate(R.layout.adapter_choicenebook_header, null);
        rlHeader = view.findViewById(R.id.rlHeader);
        ivLeftIMG = view.findViewById(R.id.ivLeftIMG);
        tvLeftTitle = view.findViewById(R.id.tvLeftTitle);
        tvRightTitle = view.findViewById(R.id.tvRightTitle);
        ivRightIMG = view.findViewById(R.id.ivRightIMG);
    }

    /**
     * 无数据页面
     *
     * @return
     */
    public View getEmptyView() {
        View viewEmpty = LayoutInflater.from(getContext()).inflate(R.layout.empty_booklist, null);
        ImageView ivIMG = viewEmpty.findViewById(R.id.ivEmptyPic);
        ivIMG.setBackgroundResource(R.mipmap.ic_booklistempty);
        return viewEmpty;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        type = "";
        category = "";
        label = "";
    }
}
